<!-- 参保人员费用查询页面 -->
<template>
  <div class="cost-query-page">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input 
            v-model="searchForm.idCard" 
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="住院号">
          <el-input 
            v-model="searchForm.hospitalNumber" 
            placeholder="请输入住院号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 左侧：参保人员列表 -->
      <el-card class="personnel-card">
        <template #header>
          <span>参保人员信息</span>
        </template>
        
        <el-table 
          :data="personnelList" 
          v-loading="personnelLoading"
          highlight-current-row
          @current-change="handlePersonnelSelect"
          style="width: 100%"
          height="600"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="hospitalNumber" label="住院号" width="120" align="center" />
          <el-table-column prop="name" label="姓名" width="100" align="center" />
          <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
          <el-table-column prop="gender" label="性别" width="60" align="center" />
          <el-table-column prop="age" label="年龄" width="60" align="center" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="searchForm.pageNum"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 50]"
            :total="personnelTotal"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
          />
        </div>
      </el-card>

      <!-- 右侧：费用详情 -->
      <el-card class="cost-detail-card">
        <template #header>
          <span>费用详情</span>
          <span v-if="selectedPersonnel" class="selected-info">
            - {{ selectedPersonnel.name }}（{{ selectedPersonnel.hospitalNumber }}）
          </span>
        </template>
        
        <div v-if="!selectedPersonnel" class="no-selection">
          <el-empty description="请选择参保人员查看费用详情" />
        </div>
        
        <div v-else class="cost-tabs">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <!-- 药品费用 -->
            <el-tab-pane label="药品费用" name="drugs">
              <el-table 
                :data="drugOrderList" 
                v-loading="drugLoading"
                stripe
                border
                style="width: 100%"
                :summary-method="getDrugSummary"
                show-summary
              >
                <el-table-column prop="drugName" label="药品名称" min-width="150" />
                <el-table-column prop="tradeName" label="商品名" min-width="120" />
                <el-table-column prop="specification" label="规格" width="120" />
                <el-table-column prop="classification" label="分类" width="80" align="center">
                  <template #default="{ row }">
                    <el-tag 
                      :type="row.classification === '甲' ? 'success' : row.classification === '乙' ? 'warning' : 'danger'"
                      size="small"
                    >
                      {{ row.classification }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="quantity" label="数量" width="80" align="center" />
                <el-table-column prop="unit" label="单位" width="80" align="center" />
                <el-table-column prop="paymentStandard" label="单价" width="100" align="right">
                  <template #default="{ row }">
                    ¥{{ row.paymentStandard?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ row.totalAmount?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
                <el-table-column prop="orderTime" label="开具时间" width="180" align="center">
                  <template #default="{ row }">
                    {{ formatDateTime(row.orderTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="doctorName" label="医生" width="100" align="center" />
              </el-table>
            </el-tab-pane>

            <!-- 诊疗项目费用 -->
            <el-tab-pane label="诊疗项目" name="services">
              <el-table 
                :data="serviceOrderList" 
                v-loading="serviceLoading"
                stripe
                border
                style="width: 100%"
                :summary-method="getServiceSummary"
                show-summary
              >
                <el-table-column prop="projectName" label="诊疗项目名称" min-width="150" />
                <el-table-column prop="projectCode" label="项目编码" width="120" align="center" />
                <el-table-column prop="quantity" label="数量" width="80" align="center" />
                <el-table-column prop="unitOfMeasure" label="单位" width="80" align="center" />
                <el-table-column prop="price" label="单价" width="100" align="right">
                  <template #default="{ row }">
                    ¥{{ row.price?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ row.totalAmount?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
                <el-table-column prop="orderTime" label="开具时间" width="180" align="center">
                  <template #default="{ row }">
                    {{ formatDateTime(row.orderTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="doctorName" label="医生" width="100" align="center" />
              </el-table>
            </el-tab-pane>

            <!-- 医疗服务费用 -->
            <el-tab-pane label="医疗服务" name="treatments">
              <el-table 
                :data="treatmentOrderList" 
                v-loading="treatmentLoading"
                stripe
                border
                style="width: 100%"
                :summary-method="getTreatmentSummary"
                show-summary
              >
                <el-table-column prop="projectName" label="医疗服务名称" min-width="150" />
                <el-table-column prop="projectCode" label="服务编码" width="120" align="center" />
                <el-table-column prop="quantity" label="数量" width="80" align="center" />
                <el-table-column prop="pricingUnit" label="单位" width="80" align="center" />
                <el-table-column prop="price" label="单价" width="100" align="right">
                  <template #default="{ row }">
                    ¥{{ row.price?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
                  <template #default="{ row }">
                    ¥{{ row.totalAmount?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
                <el-table-column prop="orderTime" label="开具时间" width="180" align="center">
                  <template #default="{ row }">
                    {{ formatDateTime(row.orderTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="doctorName" label="医生" width="100" align="center" />
              </el-table>
            </el-tab-pane>

            <!-- 费用汇总 -->
            <el-tab-pane label="费用汇总" name="summary">
              <div class="cost-summary">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-card class="summary-card">
                      <template #header>
                        <span>药品费用</span>
                      </template>
                      <div class="summary-content">
                        <div class="amount">¥{{ drugTotalAmount.toFixed(2) }}</div>
                        <div class="count">{{ drugOrderList.length }} 项</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :span="8">
                    <el-card class="summary-card">
                      <template #header>
                        <span>诊疗项目费用</span>
                      </template>
                      <div class="summary-content">
                        <div class="amount">¥{{ serviceTotalAmount.toFixed(2) }}</div>
                        <div class="count">{{ serviceOrderList.length }} 项</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :span="8">
                    <el-card class="summary-card">
                      <template #header>
                        <span>医疗服务费用</span>
                      </template>
                      <div class="summary-content">
                        <div class="amount">¥{{ treatmentTotalAmount.toFixed(2) }}</div>
                        <div class="count">{{ treatmentOrderList.length }} 项</div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
                <el-card class="total-summary-card">
                  <template #header>
                    <span>总费用</span>
                  </template>
                  <div class="total-summary-content">
                    <div class="total-amount">¥{{ totalAmount.toFixed(2) }}</div>
                    <div class="total-count">{{ totalCount }} 项</div>
                  </div>
                </el-card>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getPersonnelList } from '@/api/personnel'
import { getPatientDrugOrders, getPatientServiceOrders, getPatientTreatmentOrders } from '@/api/cost-query'

// 响应式数据
const personnelLoading = ref(false)
const drugLoading = ref(false)
const serviceLoading = ref(false)
const treatmentLoading = ref(false)

const personnelList = ref([])
const personnelTotal = ref(0)
const selectedPersonnel = ref(null)

const drugOrderList = ref([])
const serviceOrderList = ref([])
const treatmentOrderList = ref([])

const activeTab = ref('drugs')

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  idCard: '',
  hospitalNumber: ''
})

// 计算属性 - 费用汇总
const drugTotalAmount = computed(() => {
  return drugOrderList.value.reduce((sum, item) => sum + (Number(item.totalAmount) || 0), 0)
})

const serviceTotalAmount = computed(() => {
  return serviceOrderList.value.reduce((sum, item) => sum + (Number(item.totalAmount) || 0), 0)
})

const treatmentTotalAmount = computed(() => {
  return treatmentOrderList.value.reduce((sum, item) => sum + (Number(item.totalAmount) || 0), 0)
})

const totalAmount = computed(() => {
  return drugTotalAmount.value + serviceTotalAmount.value + treatmentTotalAmount.value
})

const totalCount = computed(() => {
  return drugOrderList.value.length + serviceOrderList.value.length + treatmentOrderList.value.length
})

// 获取参保人员列表
const fetchPersonnelList = async () => {
  personnelLoading.value = true
  try {
    const response = await getPersonnelList(searchForm)
    if (response.flag) {
      personnelList.value = response.data.records || []
      personnelTotal.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取人员列表失败')
    }
  } catch (error) {
    console.error('获取人员列表失败:', error)
    ElMessage.error('获取人员列表失败')
  } finally {
    personnelLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  fetchPersonnelList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    pageNum: 1,
    pageSize: 10,
    name: '',
    idCard: '',
    hospitalNumber: ''
  })
  fetchPersonnelList()
}

// 页码改变
const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  fetchPersonnelList()
}

// 每页显示条数改变
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  searchForm.pageNum = 1
  fetchPersonnelList()
}

// 选择参保人员
const handlePersonnelSelect = (personnel) => {
  console.log('选择人员:', personnel)
  selectedPersonnel.value = personnel
  // 清空之前的数据
  drugOrderList.value = []
  serviceOrderList.value = []
  treatmentOrderList.value = []
  
  if (personnel) {
    // 根据当前激活的tab加载对应数据
    loadCostData(activeTab.value)
  }
}

// 切换tab
const handleTabChange = (tabName) => {
  if (selectedPersonnel.value) {
    loadCostData(tabName)
  }
}

// 加载费用数据
const loadCostData = async (tabName) => {
  if (!selectedPersonnel.value) return
  
  const patientId = selectedPersonnel.value.patientId
  
  try {
    switch (tabName) {
      case 'drugs':
        await loadDrugOrders(patientId)
        break
      case 'services':
        await loadServiceOrders(patientId)
        break
      case 'treatments':
        await loadTreatmentOrders(patientId)
        break
      case 'summary':
        // 加载所有数据
        await loadDrugOrders(patientId)
        await loadServiceOrders(patientId)
        await loadTreatmentOrders(patientId)
        break
    }
  } catch (error) {
    console.error('加载费用数据失败:', error)
  }
}

// 加载药品医嘱
const loadDrugOrders = async (patientId) => {
  drugLoading.value = true
  try {
    console.log('加载药品医嘱，患者ID:', patientId)
    const response = await getPatientDrugOrders(patientId)
    console.log('药品医嘱响应:', response)
    if (response.flag) {
      drugOrderList.value = response.data || []
      console.log('药品医嘱数据:', drugOrderList.value)
    } else {
      ElMessage.error(response.message || '获取药品费用失败')
    }
  } catch (error) {
    console.error('获取药品费用失败:', error)
    ElMessage.error('获取药品费用失败')
  } finally {
    drugLoading.value = false
  }
}

// 加载诊疗服务医嘱
const loadServiceOrders = async (patientId) => {
  serviceLoading.value = true
  try {
    console.log('加载诊疗服务医嘱，患者ID:', patientId)
    const response = await getPatientServiceOrders(patientId)
    console.log('诊疗服务医嘱响应:', response)
    if (response.flag) {
      serviceOrderList.value = response.data || []
      console.log('诊疗服务医嘱数据:', serviceOrderList.value)
    } else {
      ElMessage.error(response.message || '获取诊疗项目费用失败')
    }
  } catch (error) {
    console.error('获取诊疗项目费用失败:', error)
    ElMessage.error('获取诊疗项目费用失败')
  } finally {
    serviceLoading.value = false
  }
}

// 加载医疗服务医嘱
const loadTreatmentOrders = async (patientId) => {
  treatmentLoading.value = true
  try {
    console.log('加载医疗服务医嘱，患者ID:', patientId)
    const response = await getPatientTreatmentOrders(patientId)
    console.log('医疗服务医嘱响应:', response)
    if (response.flag) {
      treatmentOrderList.value = response.data || []
      console.log('医疗服务医嘱数据:', treatmentOrderList.value)
    } else {
      ElMessage.error(response.message || '获取医疗服务费用失败')
    }
  } catch (error) {
    console.error('获取医疗服务费用失败:', error)
    ElMessage.error('获取医疗服务费用失败')
  } finally {
    treatmentLoading.value = false
  }
}

// 药品费用合计计算
const getDrugSummary = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (column.property === 'totalAmount') {
      const values = data.map(item => Number(item[column.property]))
      sums[index] = `¥${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0).toFixed(2)}`
    } else if (column.property === 'quantity') {
      const values = data.map(item => Number(item[column.property]))
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 诊疗服务费用合计计算
const getServiceSummary = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (column.property === 'totalAmount') {
      const values = data.map(item => Number(item[column.property]))
      sums[index] = `¥${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0).toFixed(2)}`
    } else if (column.property === 'quantity') {
      const values = data.map(item => Number(item[column.property]))
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 医疗服务费用合计计算
const getTreatmentSummary = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (column.property === 'totalAmount') {
      const values = data.map(item => Number(item[column.property]))
      sums[index] = `¥${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0).toFixed(2)}`
    } else if (column.property === 'quantity') {
      const values = data.map(item => Number(item[column.property]))
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  fetchPersonnelList()
})
</script>

<style scoped>
.cost-query-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.main-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 200px);
}

.personnel-card {
  width: 500px;
  min-width: 500px;
}

.cost-detail-card {
  flex: 1;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.selected-info {
  color: #409eff;
  font-weight: normal;
}

.no-selection {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cost-tabs {
  height: calc(100vh - 320px);
  overflow: auto;
}

.cost-summary {
  padding: 20px;
}

.summary-card {
  margin-bottom: 20px;
}

.summary-content {
  text-align: center;
}

.amount {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.count {
  color: #999;
  font-size: 14px;
}

.total-summary-card {
  margin-top: 20px;
}

.total-summary-content {
  text-align: center;
}

.total-amount {
  font-size: 36px;
  font-weight: bold;
  color: #e6a23c;
  margin-bottom: 10px;
}

.total-count {
  color: #999;
  font-size: 16px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

:deep(.el-tabs__content) {
  height: calc(100% - 40px);
  overflow: auto;
}
</style>
